<template>
  <div class="roles">
    <qwerty title1='权限管理' title2='角色列表'></qwerty>
  <el-card style="margin-top:20px">
    <el-row :gutter="20">
  <el-col :span="6">
   <el-button type="primary" @click="add">添加用户</el-button>
  </el-col>
</el-row>
    <el-table
    :data="tableData"
    stripe
    style="width: 100%;margin-top:20px">
    <el-table-column type="expand">
      <template slot-scope="scope">
        <el-row class="vcenter" :class="index==0 ? '' : 'bdtop'" :gutter="20" v-for="(level1,index) in scope.row.children" :key="level1.id">
          <el-col :span="5">
            <el-tag>{{level1.authName}}</el-tag>
          </el-col>
          <el-col :span="19">
              <el-row  v-for="(level2,index) in level1.children" :key="level2.id">
                <el-col :span="6">
                  <el-tag @close="removeRolesById(scope.row,level2.id)" closable type="success">{{level2.authName}}</el-tag>
                </el-col>
                <el-col class="vcenter" :class="index==0 ? '' : 'bdtop'" :span="18">
                  <el-tag @close="removeRolesById(scope.row,level3.id)" closable type="warning"  v-for="level3 in level2.children" :key="level3.id">{{level3.authName}}</el-tag>
                </el-col>
              </el-row>
          </el-col>
        </el-row>
      </template>
    </el-table-column>
    <el-table-column type="index">
        </el-table-column>
    <el-table-column prop="roleName" label="角色名称">
        </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述">
        </el-table-column>
        <el-table-column label="操作">
           <template slot-scope="scope">
             <el-button type="primary"
                         icon="el-icon-edit"
                         size="mini"
                         @click="handleEdit(scope.row)">
                         编辑
                        </el-button>
          <el-button type="danger"
                         icon="el-icon-delete"
                         size="mini"
                         @click="handleDelete(scope.row)">删除
                        </el-button>
          <el-tooltip effect="dark"
                         content="分配权限"
                         placement="top"
                         :enterable="false">
                          <el-button
                          type="warning"
                          icon="el-icon-setting"
                          @click="handleRoleEdit(scope.row)"
                          size="mini">分配权限
                          </el-button>
                        </el-tooltip>  
      </template>
        </el-table-column>
  </el-table>
  </el-card>
  <el-dialog :title="title" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
            <span>
                <el-form :model="ruleForm" :rules="rules" ref="addForm" label-width="100px" class="demo-ruleForm">
                    <el-form-item label="角色名称" prop="roleName">
                      <el-input v-model="ruleForm.roleName"></el-input>
                    </el-form-item>
                    <el-form-item label="角色描述" prop="roleDesc">
                      <el-input v-model="ruleForm.roleDesc"></el-input>
                    </el-form-item>
                  </el-form>
            </span>
            <span slot="footer" class="dialog-footer">
    <el-button @click="handleClose">取 消</el-button>
    <el-button type="primary" @click="addRole('addForm')">确 定</el-button>
  </span>
        </el-dialog>
        <el-dialog title="分配权限" :visible.sync="dialogVisible2" width="30%" :before-close="handleClose">
            <span>
                <el-tree
                ref="treeRef"
                  :data="data"
                  show-checkbox
                  node-key="id"
                  default-expand-all
                  :default-checked-keys="defKeys"
                  :props="defaultProps">
                </el-tree>
            </span>
            <span slot="footer" class="dialog-footer">
    <el-button @click="handleClose">取 消</el-button>
    <el-button type="primary" @click="allotRights">确 定</el-button>
  </span>
        </el-dialog>
  </div>
</template>

<script>
import {getRoles,deleteRoles,getRightsTree,addRoles,addOrPutRole,getRolesById,deleteRolesById} from '@/api/power'
export default {
  name: 'roles',
  created(){
   this.select();
  },
  data(){
    return{
      defKeys:[],
      data:[],
      defaultProps: {
          children: 'children',
          label: 'authName'
        },
        title:'',
        isShow:true,      
        user:'',
        dialogVisible: false,
        dialogVisible2: false,
        pageNum: 1,
        pageSize: 8,
        total: 0,
        tableData: [],
        ruleForm: {
            roleId: '',
            roleName: '',
            roleDesc: ''
        },
        rules: {
            roleName: [{
                required: true,
                message: '请输入用户名',
                trigger: 'blur'
            }],
            roleDesc: [{
                required: true,
                message: '请输入邮箱',
                trigger: 'blur'
            }]
        },
        roleId:''
    }
  },
  methods:{
    async allotRights(){
     const keys=[
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ];
      const keyId=keys.join(',');
      var {data:res}=await addRoles(`roles/${this.roleId}/rights`,{rids:keyId});
      if(res.meta.status==200){
         this.$message({
            message: res.meta.msg,
            type: 'success'
          });
          this.select();
          this.dialogVisible2=false;
      }
    },
    add(){
      this.isShow=true;
      this.dialogVisible=true;
      this.title='添加'
    },
    async addRole(addForm) {
      this.$refs[addForm].validate(async (valid) => {
          if (valid) {
            var msg='';
            if(this.ruleForm.roleId!=''){
              var {data:res}=await addOrPutRole(`roles/${this.ruleForm.roleId}`,'put',{
                roleName:this.ruleForm.roleName,
                roleDesc:this.ruleForm.roleDesc
              })
               msg='修改'
            }else{
              var {data:res}=await addOrPutRole("roles",'post',this.ruleForm)
               msg='添加'
            }
               if(res.meta.status==201){
                    this.$message({
                      message:msg+'成功！',
                      type: 'success'
                    });
                    this.dialogVisible = false;
                    this.select();
                    this.handleClose();
                }else if(res.meta.status==200){
                    this.$message({
                      message: msg+'成功！',
                      type: 'success'
                    });
                    this.dialogVisible = false;
                    this.select();
                    this.handleClose();
                }else{
                    this.$message({
                      message:msg+'失败',
                      type: 'error'
                    });
                }
              
          } else {
              console.log('error submit!!');
              return false;
          }
      });
     },
     handleClose() {
        // this.$refs['addForm'].resetFields();
        this.ruleForm.roleId ='';
        this.ruleForm.roleName = '';
        this.ruleForm.roleDesc = '';
        this.defKeys=[];
        this.dialogVisible = false;
        this.dialogVisible2 = false;
    },
    async handleEdit(row){
      this.dialogVisible = true;
      var {data:res} = await getRolesById(`roles/${row.id}`);
      console.log(res)
      this.ruleForm.roleId = res.data.roleId;
      this.ruleForm.roleName = res.data.roleName;
      this.ruleForm.roleDesc = res.data.roleDesc;
      this.ruleForm.mobile = res.data.mobile;
      this.title='修改'
    },
    async handleDelete(row){
        this.$confirm('确认删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          var {data:res}=await deleteRolesById(`roles/${row.id}`)
            if(res.meta.status==200){
              this.$message({
                 message: res.meta.msg,
                 type: 'success'
              })
              this.select();
            }else{
              this.$message({
                 message: res.meta.msg,
                 type: 'error'
              })
            }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    async select(){
      var {data:res}= await getRoles()
      this.tableData=res.data;
    },
    async removeRolesById(row,rightId){
      this.$confirm('确认删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          var {data:res}=await deleteRoles(`roles/${row.id}/rights/${rightId}`)
            if(res.meta.status==200){
              this.$message({
                 message: res.meta.msg,
                 type: 'success'
              })
              row.children=res.data;
            }else{
              this.$message({
                 message: res.meta.msg,
                 type: 'error'
              })
            }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    getLeafKeys(node,arr){
      if(!node.children){
        return arr.push(node.id);
      }
      node.children.forEach((item) => this.getLeafKeys(item,arr));
    },
    async handleRoleEdit(row){
      this.getLeafKeys(row,this.defKeys)
      var {data:res}= await getRightsTree();
      this.data=res.data
      this.roleId=row.id
      this.dialogVisible2=true;
    }
  }
}
</script>

<style scoped>
  .el-tag{
    margin: 10px;
  }
  .vcenter{
    display: flex;;
    align-items: center;
  }
  .bdtop{
    border-top: 1px solid #eee;
  }
</style>
